import { z } from 'zod'
import dotenv from 'dotenv'

// 加载环境变量
dotenv.config()

// 环境变量验证模式
const envSchema = z.object({
  // 应用配置
  NODE_ENV: z.enum(['development', 'production', 'test']).default('development'),
  PORT: z.string().transform(Number).default('3000'),
  HOST: z.string().default('localhost'),
  API_VERSION: z.string().default('v1'),

  // 数据库配置
  DATABASE_URL: z.string().min(1, 'Database URL is required'),
  DATABASE_POOL_SIZE: z.string().transform(Number).default('10'),

  // Redis 配置
  REDIS_URL: z.string().min(1, 'Redis URL is required'),
  REDIS_PREFIX: z.string().default('bai-hu:'),

  // JWT 配置
  JWT_SECRET: z.string().min(32, 'JWT secret must be at least 32 characters'),
  JWT_EXPIRES_IN: z.string().default('15m'),
  JWT_REFRESH_EXPIRES_IN: z.string().default('7d'),
  JWT_ISSUER: z.string().default('bai-hu-cloud'),
  JWT_AUDIENCE: z.string().default('bai-hu-api'),

  // API 密钥配置
  API_KEY_SECRET: z.string().min(32, 'API key secret must be at least 32 characters'),

  // 文件存储配置
  STORAGE_TYPE: z.enum(['local', 'minio', 's3']).default('local'),
  STORAGE_PATH: z.string().default('./uploads'),
  MAX_FILE_SIZE: z.string().transform(Number).default('104857600'), // 100MB

  // MinIO 配置
  MINIO_ENDPOINT: z.string().optional(),
  MINIO_PORT: z.string().transform(Number).optional(),
  MINIO_ACCESS_KEY: z.string().optional(),
  MINIO_SECRET_KEY: z.string().optional(),
  MINIO_BUCKET: z.string().optional(),
  MINIO_USE_SSL: z.string().transform(Boolean).default('false'),

  // AWS S3 配置
  AWS_REGION: z.string().optional(),
  AWS_ACCESS_KEY_ID: z.string().optional(),
  AWS_SECRET_ACCESS_KEY: z.string().optional(),
  S3_BUCKET: z.string().optional(),

  // 邮件配置
  SMTP_HOST: z.string().default('localhost'),
  SMTP_PORT: z.string().transform(Number).default('1025'),
  SMTP_USER: z.string().optional(),
  SMTP_PASS: z.string().optional(),
  SMTP_FROM: z.string().default('noreply@plugin-cloud.com'),
  SMTP_SECURE: z.string().transform(Boolean).default('false'),

  // 安全配置
  BCRYPT_ROUNDS: z.string().transform(Number).default('12'),
  RATE_LIMIT_WINDOW_MS: z.string().transform(Number).default('900000'), // 15分钟
  RATE_LIMIT_MAX_REQUESTS: z.string().transform(Number).default('1000'),
  CORS_ORIGINS: z.string().default('http://localhost:5173,http://localhost:3000'),

  // 插件安全配置
  PLUGIN_SCAN_ENABLED: z.string().transform(Boolean).default('true'),
  PLUGIN_SIGNATURE_REQUIRED: z.string().transform(Boolean).default('false'),
  PLUGIN_MAX_SIZE: z.string().transform(Number).default('104857600'), // 100MB

  // 监控配置
  METRICS_ENABLED: z.string().transform(Boolean).default('true'),
  LOG_LEVEL: z.enum(['debug', 'info', 'warn', 'error']).default('info'),
  LOG_FORMAT: z.enum(['json', 'simple']).default('json'),

  // 外部服务
  VIRUS_SCAN_API_URL: z.string().optional(),
  VIRUS_SCAN_API_KEY: z.string().optional(),

  // 开发配置
  DEV_SEED_DATA: z.string().transform(Boolean).default('false'),
  DEV_AUTO_APPROVE_PLUGINS: z.string().transform(Boolean).default('false'),
})

// 验证环境变量
const envResult = envSchema.safeParse(process.env)

if (!envResult.success) {
  console.error('❌ Invalid environment variables:')
  console.error(envResult.error.format())
  process.exit(1)
}

const env = envResult.data

// 导出配置对象
export const config = {
  // 应用配置
  nodeEnv: env.NODE_ENV,
  port: env.PORT,
  host: env.HOST,
  apiVersion: env.API_VERSION,
  isDevelopment: env.NODE_ENV === 'development',
  isProduction: env.NODE_ENV === 'production',
  isTest: env.NODE_ENV === 'test',

  // 数据库配置
  database: {
    url: env.DATABASE_URL,
    poolSize: env.DATABASE_POOL_SIZE,
  },

  // Redis 配置
  redis: {
    url: env.REDIS_URL,
    prefix: env.REDIS_PREFIX,
  },

  // JWT 配置
  jwt: {
    secret: env.JWT_SECRET,
    expiresIn: env.JWT_EXPIRES_IN,
    refreshExpiresIn: env.JWT_REFRESH_EXPIRES_IN,
    issuer: env.JWT_ISSUER,
    audience: env.JWT_AUDIENCE,
  },

  // API 密钥配置
  apiKey: {
    secret: env.API_KEY_SECRET,
  },

  // 文件存储配置
  storage: {
    type: env.STORAGE_TYPE,
    path: env.STORAGE_PATH,
    maxFileSize: env.MAX_FILE_SIZE,
    minio: {
      endpoint: env.MINIO_ENDPOINT,
      port: env.MINIO_PORT,
      accessKey: env.MINIO_ACCESS_KEY,
      secretKey: env.MINIO_SECRET_KEY,
      bucket: env.MINIO_BUCKET,
      useSSL: env.MINIO_USE_SSL,
    },
    s3: {
      region: env.AWS_REGION,
      accessKeyId: env.AWS_ACCESS_KEY_ID,
      secretAccessKey: env.AWS_SECRET_ACCESS_KEY,
      bucket: env.S3_BUCKET,
    },
  },

  // 邮件配置
  smtp: {
    host: env.SMTP_HOST,
    port: env.SMTP_PORT,
    user: env.SMTP_USER,
    pass: env.SMTP_PASS,
    from: env.SMTP_FROM,
    secure: env.SMTP_SECURE,
  },

  // 安全配置
  security: {
    bcryptRounds: env.BCRYPT_ROUNDS,
    rateLimitWindowMs: env.RATE_LIMIT_WINDOW_MS,
    rateLimitMaxRequests: env.RATE_LIMIT_MAX_REQUESTS,
    pluginScanEnabled: env.PLUGIN_SCAN_ENABLED,
    pluginSignatureRequired: env.PLUGIN_SIGNATURE_REQUIRED,
    pluginMaxSize: env.PLUGIN_MAX_SIZE,
  },

  // CORS 配置
  cors: {
    origins: env.CORS_ORIGINS.split(',').map(origin => origin.trim()),
  },

  // 监控配置
  monitoring: {
    metricsEnabled: env.METRICS_ENABLED,
    logLevel: env.LOG_LEVEL,
    logFormat: env.LOG_FORMAT,
  },

  // 外部服务配置
  external: {
    virusScan: {
      apiUrl: env.VIRUS_SCAN_API_URL,
      apiKey: env.VIRUS_SCAN_API_KEY,
    },
  },

  // 开发配置
  dev: {
    seedData: env.DEV_SEED_DATA,
    autoApprovePlugins: env.DEV_AUTO_APPROVE_PLUGINS,
  },
} as const

// 类型导出
export type Config = typeof config
